// -----------------------------
// Author: 		Dhaenens Gert	
// Creation: 	11/24/2014 1:21:01 PM				
// -----------------------------

#include "Thread.h"

DWORD WINAPI Thread::ThreadProc(void* lpParam)
{
	// Get the Thread Object
	Thread* lpThread = reinterpret_cast<Thread*>(lpParam);
	// Get the Args & Callback
	Thread::ThreadCallback callback = lpThread->m_fnCallback;
	Thread::ThreadArgs args = lpThread->m_Args;

	// Invoke the Callback
	callback(lpThread, args.lpArgs);

	// Set the running to false
	lpThread->m_bIsRunning = false;

	return 0;
}

Thread::Thread()
	: m_dwThreadId(0)
	, m_hThread(NULL)
	, m_bIsRunning(false)
	, m_bIsSuspended(false)
{
}

Thread::~Thread()
{
}

Bool Thread::Start(ThreadCallback fnThreadCallback, void* lpArgs)
{
	m_Args.Thread = this;
	m_Args.lpArgs = lpArgs;
	m_fnCallback = fnThreadCallback;

	m_hThread = CreateThread(NULL, 0, Thread::ThreadProc, this, 0, &m_dwThreadId);
	if (m_hThread)
		m_bIsRunning = true;
	return m_bIsRunning;
}
Bool Thread::Stop()
{
	if (m_hThread)
	{
		TerminateThread(m_hThread, 0);
		m_hThread = NULL;
		m_dwThreadId = 0;
		m_bIsRunning = false;
	}
	return true;
}
Bool Thread::Suspend()
{
	if (m_hThread && !m_bIsSuspended)
	{
		SuspendThread(m_hThread);
		m_bIsSuspended = true;
	}
	return true;
}
Bool Thread::Resume()
{
	if (m_hThread && m_bIsSuspended)
	{
		ResumeThread(m_hThread);
		m_bIsSuspended = false;
	}
	return true;
}

Bool Thread::IsRunning() const
{
	return m_bIsRunning;
}
Bool Thread::IsSuspended() const
{
	return m_bIsSuspended;
}